package personal.jinhui.paprika.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.jivesoftware.smack.util.StringUtils;

import personal.jinhui.paprika.PaprikaApplication;
import personal.jinhui.paprika.ui.LoginActivity;
import personal.jinhui.paprika.ui.SettingsActivity;

import personal.jinhui.paprika.R;

public class LoginActivity extends Activity implements OnClickListener {
	private static final String TAG = "LoginActivity";

	private static final int LOGIN_REQUEST_CODE = 1;
	private Button mLoginButton;
	private EditText mUsername;
	private EditText mPassword;
	private boolean mValidUsername;
	private boolean mValidPassword;

	private PaprikaApplication mPaprikaApplication;
	private SharedPreferences mSettings;

	/**
	 * Constructor.
	 */
	public LoginActivity() {
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Application app = getApplication();
		if (app instanceof PaprikaApplication) {
			mPaprikaApplication = (PaprikaApplication) app;
			if (mPaprikaApplication.isConnected()) {
				startActivity(new Intent(this, HomeActivity.class));
				finish();
			}
			else {
				setContentView(R.layout.login);

				mLoginButton = (Button) findViewById(R.id.login);
				mLoginButton.setOnClickListener(this);
				mUsername = (EditText) findViewById(R.id.username);
				mPassword = (EditText) findViewById(R.id.password);

				getWindow()
						.setSoftInputMode(
								WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
				// InputMethodManager imm =
				// (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				// imm.hideSoftInputFromWindow(mUsername.getWindowToken(), 0);

				mSettings = PreferenceManager.getDefaultSharedPreferences(this);
			}
		}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		mUsername.setText(mSettings.getString("username", ""));
		mPassword.setText(mSettings.getString("password", ""));
	}

	@Override
	public void onClick(View v) {
		if (v == mLoginButton) {
			checkUsername(mUsername.getText().toString());
			checkPassword(mPassword.getText().toString());
			if (mValidUsername && mValidPassword && checkServerAddrandPort()) {
				Intent i = new Intent(this, LoginAnimActivity.class);
				configureAccount();
				startActivityForResult(i, LOGIN_REQUEST_CODE);
			} else {
				Toast.makeText(LoginActivity.this, R.string.account_invalid,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == LOGIN_REQUEST_CODE) {
			if (resultCode == Activity.RESULT_OK) {
				startActivity(new Intent(this, HomeActivity.class));
				finish();
			} else if (resultCode == Activity.RESULT_CANCELED) {
				if (data != null) {
					Toast.makeText(LoginActivity.this, data.getExtras().getString("message"), Toast.LENGTH_SHORT)
							.show();
				}
			}
		}
	}

	/**
	 * Store the account in the settings.
	 */
	private void configureAccount() {
		SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor edit = pref.edit();
		if ((mSettings.getString("username", "").equals(mUsername
				.getText().toString()))
				&& (mSettings.getString("password", "")
						.equals(mPassword.getText().toString()))) {
			Log.v(TAG, "account not change!");
		}
		edit.putString("username", mUsername.getText().toString());
		edit.putString("password", mPassword.getText()
				.toString());
		edit.commit();
	}

	private boolean checkServerAddrandPort() {		
		if ((mSettings.getString("xmpp_server", "").equals(""))
				|| (mSettings.getString("xmpp_port", "").equals(""))){
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * Check that the username is really a JID.
	 * 
	 * @param username
	 *            the username to check.
	 */
	private void checkUsername(String username) {
		if (username.length() > 0)
			mValidUsername= true;
		else
			mValidUsername = false;
	}

	/**
	 * Check password.
	 * 
	 * @param password
	 *            the password to check.
	 */
	private void checkPassword(String password) {
		if (password.length() > 0)
			mValidPassword = true;
		else
			mValidPassword = false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.login, menu);
		return true;
	}

	@Override
	public final boolean onOptionsItemSelected(MenuItem item) {
		boolean result;
		switch (item.getItemId()) {
		case R.id.login_menu_settings:
			startActivity(new Intent(this, SettingsActivity.class));
			result = true;
			break;
		case R.id.login_menu_about:
			createAboutDialog();
			result = true;
			break;
		default:
			result = false;
			break;
		}
		return result;
	}

	/**
	 * Create an about "Paprika" dialog.
	 */
	private void createAboutDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		String versionname;
		try {
			PackageManager pm = getPackageManager();
			PackageInfo pi = pm.getPackageInfo("personal.jinhui.paprika",
					PackageManager.PERMISSION_GRANTED);
			versionname = pi.versionName;
		} catch (PackageManager.NameNotFoundException e) {
			versionname = "";
		}
		String title = getString(R.string.login_about_title, versionname);
		builder.setTitle(title).setMessage(R.string.login_about_msg)
				.setCancelable(false);
		builder.setNeutralButton(R.string.login_about_button,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.cancel();
					}
				});
		AlertDialog aboutDialog = builder.create();
		aboutDialog.show();
	}
}
